package com.it.security.utils;

import com.alibaba.fastjson.JSON;
import com.it.security.JWTUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @program: learning
 * @description: security 整合jwt
 * @author: Lefnmg
 * @create: 2018-11-19 23:55
 **/
@ConfigurationProperties("jwt.token")
@Component
@Data
public class JwtAuthUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String secretKey;
    private long expire;
    private static final String CLAIM_KEY_USER_ID = "user_id";
    private static final String CLAIM_KEY_AUTHORITIES = "scope";

    /**
     * 生成jwt token
     */
    public String generateToken(JWTUser user) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        Map<String, Object> claims = new HashMap<>(16);
        claims.put(CLAIM_KEY_USER_ID, user.getUserId());
        System.out.println(user.getAuthorities());
        List list = authoritiesToArray(user.getAuthorities());
        claims.put(CLAIM_KEY_AUTHORITIES,JSON.toJSON(list));
        return Jwts.builder()
//                .setClaims(claims)
                .setHeaderParam("typ", "JWT")
                .setSubject(user.getUsername())
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
    }

    public Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(secretKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    /**
     * @param claims
     * @return
     */
    public JWTUser getJWTUserByToken(Claims claims) {
        List roles = (List) claims.get(CLAIM_KEY_AUTHORITIES);
        return new JWTUser((Long) claims.get("CLAIM_KEY_USER_ID"), null, claims.getSubject(),null);
    }

    private Collection<? extends GrantedAuthority> parseArrayToAuthorities(List roles) {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        SimpleGrantedAuthority authority;
        for (Object role : roles) {
            authority = new SimpleGrantedAuthority(role.toString());
            authorities.add(authority);
        }
        return authorities;
    }
    private List authoritiesToArray(Collection<? extends GrantedAuthority> authorities) {
        List<String> list = new ArrayList<>();
        for (GrantedAuthority ga : authorities) {
            list.add(ga.getAuthority());
        }
        return list;
    }

}
